<?php

namespace App\Http\Controllers\Manage;

use App\Model\Admin;
use App\Model\LoginLog;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Mews\Captcha\Facades\Captcha;

date_default_timezone_set('PRC');
class LoginController extends Controller
{

    /**
     * 进入登录页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function login()
    {
       return view('manage.login');
        //
    }
    /**
     * 获取验证码
     * @return mixed
     */
    public function captcha()
    {
        return Captcha::create('default');
    }

    /**
     * 进入首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        return view('manage.index');
    }

    /**
     * 登录验证
     * @return mixed
     */
    public function home()
    {
        $username = Input::get('username');
        $password = Input::get('password');
        $code = Input::get('code');
        if(empty($username) || empty($password)){
            return redirect()->back()->withInput()->withErrors('用户名密码不能为空！');
        }
        if(empty($code)){
            return redirect()->back()->withInput()->withErrors('请输入验证码！');
        }
        if(Captcha::check($code) == false){
            return redirect()->back()->withInput()->withErrors('验证码错误！');
        }
        $list = Admin::where([
            ['username','=',$username],
//            ['password','=',Hash::make($password)],
        ])->first();

        if($list){
            if (!Hash::check($password, $list->password)) {
                // 密码不匹配...
                return redirect()->back()->withInput()->withErrors('密码错误！');
            }
            if($list->status != 1){
                return redirect()->back()->withInput()->withErrors('账号被禁用！登录失败！');
            }
            $getip = $this->getRealIp();  //获取ip地址
            $ip = ip2long($getip);
            if($ip != $list->ip){    //判断此次登陆的ip是否与上次登录ip相同 不同则更新到数据库
                $data['ip'] = $ip;
            }
            $number = Admin::where('id',$list->id)->increment('login_number');
            $data['login_time'] = date("Y-m-d H:i:s");
            $map = Admin::where('id',$list['id'])->update($data);
            $loginLog = LoginLog::insert([
                'role_id'=>$list['role_id'],
                'username'=>$username,
                'ip'=>$ip
            ]);
            if(!$number || !$map || !$loginLog){
                $this->error('登陆出错');
            }
            //获取用户所属角色
            $role_ids = DB::table("admin_role")->where("admin_id", $list['id'])->pluck('role_id');
            $rids = array();
            foreach ($role_ids as $id){
                $rids[] = $id;
            }
            $user = [
                'id' => $list['id'],
                'role_id' => $list['role_id'],
                'name'=> $username,
                'role_ids'=>$rids
            ];
            session(['user' => $user]);
            return Redirect::to('/');
        }else{
            return redirect()->back()->withInput()->withErrors('用户名不存在！');
        }
        //
    }

    /**
     * 注销
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function logout()
    {
        Session::flush();
        return redirect('logout');
    }

    /**
     * //获取登陆ip地址
     * @return bool
     */
    public function getRealIp(){
        $ip=false; //初始化ip为false
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){ //如果HTTP_CLIENT_IP不为空
            $ip = $_SERVER["HTTP_CLIENT_IP"]; //获取HTTP_CLIENT_IP的值
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //如果HTTP_X_FORWARDED_FOR不为空
            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);//把HTTP_X_FORWARDED_FOR的值用,分割后存放数组ips
            if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }//遍历处理
            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i]; //获得真实ip
                    break;
                }
            }
        }
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }
}